package com.algo.demo.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.List;

/**
 * ZK增删改查操作
 */
public class CrudDemo {

    public static void main(String[] args) throws Exception {
        // 创建zk客户端
        CuratorFramework client = CuratorFrameworkFactory.builder()
                                                         .connectString("172.16.1.229:2181")
                                                         .sessionTimeoutMs(3000)
                                                         .connectionTimeoutMs(3000)
                                                         .retryPolicy(new ExponentialBackoffRetry(1000 ,3))
                                                         .build();
        client.start();
        System.out.println("已经启动curator客户端");

        // 创建新节点
        client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .forPath("/my/path2", "i am path2".getBytes());

        // 获取指定节点的子节点信息
        List<String> childs = client.getChildren().forPath("/");
        System.out.println("'/'子节点为：" + childs);


        // 获取节点数据
        byte[] bytes = client.getData().forPath("/my/path");
        System.out.println("获取/my/path节点的数据内容为：" + new String(bytes));

        // 删除一个节点
        client.delete().forPath("/my/path");

        // 更新节点数据
        client.setData().forPath("/my/path2", "i am updated path2".getBytes());

        client.close();
    }

}
